package com.h4313.ghome.io;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.TreeMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;

import com.h4313.ghome.GHomeApplication;
import com.h4313.ghome.ui.dialog.HourPickerDialog.MorningConf;

public class MorningConfTask extends AsyncTask<MorningConf, Void, MorningConf> {

	public static interface MorningConfCallback {
		public void onConfRetreived(MorningConf conf, int type);
	}
	
	public static final String URL = GHomeApplication.SERVER_URL
			+ "/morning/config/%d";
	public static final int TYPE_GET = 0x01;
	public static final int TYPE_PUT = 0x02;
	
	
	private WeakReference<MorningConfCallback> mCallback = new WeakReference<MorningConfCallback>(null);
	private int mTypeRequest;
	private int mId;
	
	public MorningConfTask(MorningConfCallback callback, int id) {
		mCallback = new WeakReference<MorningConfCallback>(callback);
		mId = id;
	}
	
	public void doGet() {
		mTypeRequest = TYPE_GET;
		executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	public void doPut(MorningConf obj) {
		mTypeRequest = TYPE_PUT;
		executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, obj);
	}

	@Override
	protected MorningConf doInBackground(MorningConf... params) {

		// doGet
		if (params.length == 0) {

			try {
				String json = NetworkHelper.downloadUrl(String.format(URL, mId), 5000, 5000);
				JSONObject obj;
				obj = new JSONObject(json);
				MorningConf conf = new MorningConf();

				conf.minCoffee = obj.getInt("coffee_min");
				conf.hourCoffee = obj.getInt("coffee_hour");
				conf.minGCalendar = obj.getInt("gcalendar_min");
				conf.hourGCalendar = obj.getInt("gcalendar_hour");

				return conf;

			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;

		} else {
			MorningConf datas = params[0];

			try {
				Map<String, String> map = new TreeMap<String, String>();
				map.put("coffee_min", String.valueOf(datas.minCoffee));
				map.put("coffee_hour", String.valueOf(datas.hourCoffee));
				map.put("gcalendar_min", String.valueOf(datas.minGCalendar));
				map.put("gcalendar_hour", String.valueOf(datas.hourGCalendar));

				ServerUtilities.put(String.format(URL, mId), map);
				return datas;
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
	}

	@Override
	protected void onPostExecute(MorningConf result) {
		if (mCallback.get() != null) {
			mCallback.get().onConfRetreived(result, mTypeRequest);
		}
	}
}
